<template>
    <div class="container">
        <el-page-header @back="goBack" content="打包站列表"></el-page-header>

        <el-row type="flex" justify="space-between" class="e-m-t-45">
            <el-col :span="3" class="buttonList">
                <el-button type="primary" icon="el-icon-plus" plain @click="create">新建打包站</el-button>
            </el-col>
            <el-col class="text-right">
                <el-form :inline="true" class="demo-form-inline">
                    <el-form-item label="所属城市" prop="cityid">
                        <el-cascader separator="-" @change="SelectCity2" filterable :key="modalKey" :props="{
                            lazy: true,
                            checkStrictly: true,
                            lazyLoad: loadCity,
                            label: 'name',
                            value: 'id'
                        }" style="width: 100%;margin-right: 20px" v-model="mycityid"></el-cascader>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-select v-model="state" placeholder="请选择">
                            <el-option v-for="item in statelist" :key="item.id" :label="item.name"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="关键字">
                        <el-input placeholder="请输入" v-model="key" prefix-icon="el-icon-search"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="getList">查询</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

        <el-divider></el-divider>
        <!-- <el-row type="flex" justify="space-between" class="nav-bar e-m-b-20">
			<el-col :span="3">
				<el-button type="primary" @click="create" icon="el-icon-plus" size="small">新增</el-button>
			</el-col>
			<el-col class="text-right">
				<el-button type="primary" plain icon="el-icon-upload2" size="small">导入</el-button>
				<el-button plain icon="el-icon-download" size="small">下载</el-button>
			</el-col>
		</el-row> -->
        <el-table :data="tableData" style="width: 100%" stripe>
            <el-table-column fixed type="index" width="50">
            </el-table-column>
            <el-table-column fixed prop="name" label="打包站名称">
            </el-table-column>
            <el-table-column prop="telephone" label="联系号码" width="150">
            </el-table-column>
            <el-table-column prop="citynames" label="区域" width="230">
            </el-table-column>
            <el-table-column prop="address" label="地址" width="180">
            </el-table-column>
            <el-table-column prop="state" label="账号状态" width="150">
                <template slot-scope="scope">
                    <span class="color-success" v-if="scope.row.usestate == '已启用'">{{ scope.row.usestate }}</span>
                    <span class="color-danger" v-else>{{ scope.row.usestate }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="180">
                <template slot-scope="scope">
                    <el-button @click="views(scope.row.id)" type="text" size="small">查看</el-button>
                    <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
                    <el-button type="text" @click='startup(scope.row)' size="small">
                        <span v-if="scope.row.usestate == '已启用'">冻结</span>
                        <span v-else>启用</span>
                    </el-button>
                    <!-- <el-button type="text" @click='business(scope.row)' size="small">营业</el-button> -->
                    <!-- <el-button type="text" size="small">重置密码</el-button> -->
                </template>
            </el-table-column>
        </el-table>
        <div class="table-pagination">
            <el-pagination background layout="sizes, total, prev, pager, next" :total="total"
                :page-sizes="[10, 50, 100, 200]" :page-size="pageSize" :current-page="page" @current-change="pageChange"
                @size-change="handleSizeChange">
            </el-pagination>
        </div>
        <el-dialog :title="dialogType == 'add' ? '新建打包站' : '编辑打包站'" :visible.sync="dialogVisible" width="800px"
            z-index="99">
            <el-form ref="form" :model="form" label-width="100px" :rules="rules">
                <el-form-item label="打包站名称" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="所属城市" v-if="!dialogVisible3">
                    <el-input id='tipinput' v-model="citname" disabled placeholder="请输入城市"
                        prefix-icon="el-icon-location-information">
                        <el-button slot="append" @click="edc">修改</el-button>
                    </el-input>
                </el-form-item>
                <el-form-item label="所属城市" prop="cityid" v-if="dialogVisible3">
                    <el-cascader separator="-" @change="SelectCity" filterable :key="modalKey" :props="{
                        lazy: true,
                        checkStrictly: true,
                        lazyLoad: loadCity,
                        label: 'name',
                        value: 'id'
                    }" style="width: 100%;margin-right: 20px" v-model="form.cityid"></el-cascader>
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input id='tipinput1' v-model="form.address" placeholder="请输入地址(街道、楼牌等)"
                        prefix-icon="el-icon-location-information">
                        <el-button slot="append" icon="el-icon-search" id="geoCode" :loading="loading">搜索</el-button>
                    </el-input>
                    <div id="container" class="e-m-t-10" style="width:100%;height: 300px;"></div>
                </el-form-item>
                <el-form-item label="联系号码" prop="telephone">
                    <el-input v-model="form.telephone"></el-input>
                </el-form-item>
                <!-- <el-form-item label="性别">
                    <el-select v-model="form.sex" placeholder="请选择性别">
                        <el-option label="男" value="1"></el-option>
                        <el-option label="女" value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="身份证">
                    <cropper-upload :zoomScale='[1, 1]' :isCropper="true" @getUpload="handleFilesSuccess"
                        class="avatar-uploader">
                        <img v-if="form.identitycard" :src="fileURL + form.identitycard" class="avatar">
                        <div class="avatar-uploader-icon" v-else>
                            <div><i class="el-icon-plus"></i></div>
                            <div class="e-font-14">上传图片</div>
                        </div>
                    </cropper-upload>
                    <div class="tips e-p-t-10">建议上传尺寸比例为200*200 </div>
                </el-form-item> -->
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitType('form')">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
var map = {}
// var geocoder = {}
// var marker = {}
export default {
    layout: 'admin',
    head() {
        return {
            title: '打包站列表' 
        }
    },
    data() {
        return {
            citname:"",
            dialogVisible3:false,
            state:null,
            statelist:[
                {
                    id:null,
                    name:'全部'
                },
                {
                    id:1,
                    name:'冻结'
                },
                {
                    id:2,
                    name:'启用'
                },

            ],
            mycityid: 0,
            modalKey: 0,
            loading: true,
            key: '',
            page: 1,
            pageSize: 10,
            total: 0,
            dialogVisible: false,
            dialogType: 'add',
            form: {
                id: 0,
                cityid: 0,
                address: "",
                name: "",
                telephone: "",
                lat: 23.625349,
                lng: 113.042648,
                usestate: ""
            },
            tableData: [],
            rules: {
                name: [
                    { required: true, message: '请输入打包站名称', trigger: 'blur' },
                ],
                telephone: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                ],
                cityid: [
                    { required: true, message: '请选择城市', trigger: 'blur' },
                ],
                address: [
                    { required: true, message: '请输入街道', trigger: 'blur' },
                ],
            }

        }
    },
    mounted() {
        this.getList()
    },
    watch: {
        dialogVisible(val) {
            let that = this
            if (!val) {
                // that.form = {
                //     id:"",
                //     usestate:"",
                //     cityid: 0,
                //     address: "",
                //     name: "",
                //     telephone: "",
                //     lat:23.625349,
                //     lng:113.042648
                // }
            }
        }
    },
    methods: {
        edc(){
            this.dialogVisible3 = true
        },
        startup(row) {
            let usetate = ''
            if (row.usestate == '已冻结') {
                usetate = 2

            } else {
                usetate = 1

            }

            this.$confirm('是否修改营业状态?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$axios.post('/Admin/PackStation/Account/SetState', { ids: [row.id], state: usetate }).then(res => {
                    console.log(res)
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    this.getList()
                })
            }).catch(() => {
                // this.$message({
                //     type: 'info',
                //     message: '已取消删除'
                // });
            });
        },
        initMap() {
            let that = this

            this.$AMapLoader.load({
                key: this.AMapSetting.key,             // 申请好的Web端开发者Key，首次调用 load 时必填
                version: this.AMapSetting.version,      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
            }).then((AMap) => {
                var clickListener, map = new AMap.Map("container", {  //设置地图容器id
                    resizeEnable: true,
                    center: [this.form.lng, this.form.lat], //初始化地图中心点位置
                });

                //输入提示
                // 实例化Autocomplete
                // var autoOptions = {
                //     // input 为绑定输入提示功能的input的DOM ID
                //     city: '清远',
                //     input: 'tipinput'
                // }
                // var Autocomplete = new AMap.Autocomplete(autoOptions);

                // var placeSearch = new AMap.PlaceSearch({
                //     city: '清远',
                //     map: map
                // })
                // AMap.event.addListener(Autocomplete, 'select', (e) => {

                //     //TODO 针对选中的poi实现自己的功能
                //     placeSearch.search(e.poi.name)

                //     // e.poi.location
                //     console.log('lnglat:', e.poi.location)
                //     let lnglat = e.poi.location
                //     this.form.lat = lnglat.lat
                //     this.form.lng = lnglat.lng
                // })

                // 搜索按钮绑定事件
                var button = document.getElementById('geoCode');
                var marker = [];
                button.addEventListener("click", () => {
                    var keywords = this.form.address;

                    var autoOptions = {
                        city: '0763'
                    }
                    var placeSearch = new AMap.PlaceSearch(autoOptions);
                    placeSearch.search(keywords, function (status, result) {
                        // 搜索成功时，result即是对应的匹配数据
                        console.log('status:', status)
                        console.log('result:', result)

                        if (status == "error") {
                            if (result == "USER_DAILY_QUERY_OVER_LIMIT") {
                                that.$message.error('已超出了该高德地图api调用次数限制');
                            }
                            return
                        }

                        var pois = result.poiList.pois;
                        // 移除已创建的 marker
                        map.remove(marker);
                        marker = [];

                        for (var i = 0; i < pois.length; i++) {
                            var poi = pois[i];
                            marker[i] = new AMap.Marker({
                                position: poi.location,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                                title: poi.name
                            });
                            marker[i].content = pois[i].address
                            marker[i].location = pois[i].location
                        }
                        //将创建的点标记添加到已有的地图实例：
                        map.add(marker);
                        map.setFitView();

                        var infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
                        marker.forEach((item) => {
                            item.on('click', function (e) {
                                let obj = e.target

                                infoWindow.setContent(obj.content);
                                infoWindow.open(map, obj.location);

                                that.form.lat = obj.location.lat
                                that.form.lng = obj.location.lng
                                that.form.address = obj.content
                            });
                        })
                    })
                })

            }).catch(e => {
                console.log(e);
            })
        },
        views(id) {
            this.$router.push({
                path: '/packing/views?id=' + id
            })
        },
        SelectCity(v) { //选择城市
            this.form.cityid = v[v.length - 1];
        },
        SelectCity2(v) { //选择城市
            this.mycityid = v[v.length - 1];
        },
        loadCity(node, resolve) { //加载城市
            if (node.level == 0) {
                this.$axios.post('/city/List', {
                    pageIndex: 1,
                    pageSize: 9999,
                    pId: 0
                }).then((res) => {
                    node = res.rows.map(function (c) {
                        return {
                            id: c.id,
                            name: c.name
                        }
                    });
                    resolve(node);
                })
            } else {
                if (node.level < 4) {
                    this.$axios.post('/city/List', {
                        pageIndex: 1,
                        pageSize: 9999,
                        pId: node.value
                    }).then((res) => {
                        node = res.rows.map(function (c) {
                            return {
                                id: c.id,
                                name: c.name
                            }
                        });
                        resolve(node);
                    })
                } else {
                    resolve();
                }
            }
        },
        submitType(formName) {
            let that = this
            let api = ''
            if (this.dialogType == 'add') {
                api = '/PackStation/create'
            }
            if (this.dialogType == 'edit') {
                api = '/PackStation/edit'
            }
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.loading = true
                    this.$axios.post(api, this.form).then((res) => {
                        this.loading = false
                        this.$message.success(res.msg);
                        this.dialogVisible = false;
                        this.getList()
                    }).catch(function (error) {
                        that.loading = false
                        console.log(error, "ssss");
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });

        },
        handleFilesSuccess(res, file) {
            if (file.status === "success") {
                this.loading = false
                this.form.identitycard = res.path
            }
        },
        create() {
            this.dialogVisible = true
            this.dialogVisible3 = true
            this.dialogType = 'add'
            this.form.id = 0
            this.form.cityid = "请输入城市"
            this.form.address = ""
            this.form.name = ""
            this.form.telephone = "",
                this.form.lat = 23.625349,
                this.form.lng = 113.042648
            // this.form = {
            //     id: 0,
            //     cityid: 0,
            //     address: "",
            //     name: "",
            //     mobile: "",
            //     lat: 23.625349,
            //     lng: 113.042648
            // },
            this.initMap()
        },
        geoCode() {  //地理编码，根据地址获取经纬度坐标
            var address = this.form.address;
            var geocoder = new AMap.Geocoder({
                city: "0763", //城市设为清远，默认：“全国”
            });
            var marker = new AMap.Marker();
            this.loading = true
            geocoder.getLocation(address, (status, result) => {
                if (status === 'complete' && result.geocodes.length) {
                    var lnglat = result.geocodes[0].location
                    // document.getElementById('lnglat').value = lnglat;
                    console.log('lnglat:', lnglat)
                    marker.setPosition(lnglat);
                    map.add(marker);
                    map.setFitView(marker);
                    this.loading = false
                } else {
                    this.$message.error('根据地址查询位置失败')
                    this.loading = false
                }
            });
        },
        goBack() {
            this.$router.go(-1)
        },
        getList() {
            this.$axios.post('/PackStation/List', {
                "PageIndex": this.page,
                "PageSize": this.pageSize,
                "Key": this.key,
                "cityid": this.mycityid,
                "state": this.state
            }).then((res) => {
                console.log(res)
                this.loading = false
                res.rows.forEach((item, index) => {
                    item.citynames = item.citynames.replaceAll(",", "-")
                })
                this.tableData = res.rows;
                this.total = res.total;
            }).catch(() => {
                this.loading = false
            })
        },
        edit(item) {
            // this.modalKey++
            // this.form = item
            console.log(item.citypath.split(','),"ssss")
            let arr = item.citypath.split(',')
            console.log(item.citypath.charAt(item.citypath.length - 1), '===>')
            this.dialogType = 'edit'
            this.dialogVisible = true
            this.form.id = item.id
            this.form.name = item.name
            this.form.cityid =arr[arr.length - 1]
            this.form.address = item.address
            this.form.telephone = item.telephone
            this.form.lat = item.lat
            this.form.lng = item.lng
            this.citname = item.citynames
            this.dialogVisible3 = false

            this.initMap()

        },
        pageChange(e) { // 页码切换事件
            this.page = e;
            this.getList()
        },
        handleSizeChange(val) {
            this.page = 1;
            this.pageSize = val;
            this.getList()
        },
        del(id) {
            return new Promise((resolve, reject) => {
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // this.$axios.post('/newsDetail/delete?Ids=' + id).then((res) => {
                    //     this.$message.success(res.msg);
                    //     this.getList()
                    //     resolve()
                    // })
                })
            })

        }
    }
}
</script>

<style lang="scss" scoped>
.nav-bar {
    padding: 20px 0 0;
}

.send {
    margin-top: 15px;
    margin-right: 10px;
}

.dialogForm {
    display: flex;
    flex-wrap: wrap;

    .el-form-item {
        width: 50%;
        float: left;

        &.all {
            width: 100%;
        }

        .el-select {
            width: 100%;
        }
    }
}

.user-face {
    display: flex;
    align-items: center;
    position: relative;

    .male,
    .female {
        font-size: 14px;
        position: absolute;
        left: 30px;
        top: 0;
        background-color: #fff;
        height: 16px;
        width: 16px;
        line-height: 16px;
        border-radius: 6px;
    }

    .male {
        color: var(--blue);
    }

    .female {
        color: var(--pink);
    }
}
</style>
